<?php

namespace app\api\listener;

use app\event\CouponGifts;
use think\facade\Db;
use app\api\model\UserCoupon;
use app\api\model\Coupon;

use think\facade\Log;
use app\admin\model\User;

/**
 * 调用方式
 *
 * $save = event('couponGifts',[
 * 'user_id'   =>  1,
 * 'gifts' =>  'register'
 * ]);
 */
//   \app\api\listener\CouponGiftsListener
class CouponGiftsListener
{
    public function handle ($event)
    {
        $user = User::where([
            'id' => $event['user_id'],
        ])->find();
        if (!$user) {
            return false;
        }

        Db::startTrans();
        try {
            Coupon::where([
                'status'     => 1,
                'gifts_type' => $event['gifts'],
            ])->select()
                ->each(function ($item) use ($user) {

                    $userCoupon = new UserCoupon;
                    $time = time();
                    if ($item['aging'] == '0') {
                        # 永不过期的优惠券
                        $endTime = null;
                    } else {
                        $endTime = date("Y-m-d H:i:s", $time + $item['aging']);
                    }

                    $save = $userCoupon
                        ->create([
                            'coupon_id' => $item['coupon_id'],
                            'user_id'   => $user['id'],
                            'is_apply'  => '1',
                            'end_time'  => $endTime,
                        ]);


                    return $item;
                });

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            Log::record('[ 优惠券发放失败 ]' . "用户ID: {$event['user_id']} 状态:{$event['gifts']}");
        }


        return true;
    }
}